<template>
  <vant-form ref="form" :validate-first="true" class="page-p-l page-p-r" input-align="right">
    <app-calendar-range-field
      label="通行时间"
      v-model="form.date"
      placeholder="请选择"
      :separatorRange="separatorRange"
      :max-range="maxRange"
      :rules="[{ required:true }]"
    />
    <!-- startDate 、 endDate YYYY-MM-DD -->
    <app-picker-field
      label="起点"
      v-model="form.beginDist"
      :columns="list"
      :deep="2"
      data-type="xzqh"
      input-align="right"
      :rules="[{ required:true }]"
    ></app-picker-field>

    <app-picker-field
      label="终点"
      v-model="form.endDist"
      :columns="list"
      :deep="2"
      data-type="xzqh"
      input-align="right"
      :rules="[{ required:true }]"
    ></app-picker-field>

    <vant-field label="运输次数" :value="form.passThrough" :rules="[{ required:true }]">
      <template #input>
        <vant-radio-group v-model="form.passThrough" direction="horizontal">
          <vant-radio v-for="item in passThrough" :name="item.code" :key="item.code">{{item.text}}</vant-radio>
        </vant-radio-group>
      </template>
    </vant-field>

    <vant-search
      v-model="value"
      show-action
      input-align="left"
      placeholder="请粘贴并识别路线"
      :show-error="false"
      name="passDists"
      :rules="[{ validator}]"
      @search="onSearch"
    >
      <template #action>
        <div @click="onSearch">识别</div>
      </template>
    </vant-search>

    <ul class="passDists">
      <li v-for="(route,i) in form.passDists" :key="route._id" class="pass-item border-bottom-gray">
        <van-swipe-cell class="flex">
          <app-picker-field
            v-model="route.distCode"
            :columns="citys"
            class="city"
            rightIcon
            input-align="left"
            :rules="[{ required:true }]"
            @confirm="(v)=>confirm(v,route)"
          ></app-picker-field>
          <template>
            <vant-field
              v-if="i===0"
              v-model="route.beginPoint"
              placeholder="请输入起点"
              input-align="left"
              class="start"
              :rules="[{ required:true }]"
            />
            <span v-else class="start">{{route.beginPoint}}</span>
          </template>
          <vant-field
            v-model="route.routeDesc"
            placeholder="请输入路线"
            input-align="left"
            rows="1"
            autosize
            type="textarea"
            class="route flex-1"
            :rules="[{ required:true }]"
          />

          <template>
            <vant-field
              v-if="i===form.passDists.length-1"
              v-model="route.endPoint"
              placeholder="请输入终点"
              input-align="left"
              class="end"
              :rules="[{ required:true }]"
            />
            <span v-else class="end">{{route.endPoint}}</span>
          </template>
          <template #right>
            <vant-button
              v-if="i!==form.passDists.length-1"
              square
              text="新增"
              type="danger"
              class="delete-button"
              native-type="button"
              @click="add(route)"
            />
            <vant-button
              v-if="i!==0"
              square
              text="删除"
              type="danger"
              class="delete-button"
              native-type="button"
              @click="remove(route)"
            />
          </template>
        </van-swipe-cell>
      </li>
    </ul>

    <vant-cell class="s-btn-t60 s-btn-b20">
      <vant-button round block type="danger" @click="showHistory">历史路线</vant-button>
    </vant-cell>
    <!--  <div class="history-btn-box">
      <div class="history-btn" @click="showHistory">
        历史路线
        <vant-icon name="arrow-down" />
      </div>
    </div>-->

    <app-list-dialog ref="dialog" v-model="show" :list="historyList" @change="changeRoute">
      <template v-slot="item">
        <div>许可证号:{{item.reqNo}}</div>
        <div>车牌号码:{{item.vehicleNo}}</div>
        <div>办结时间:{{item.time}}</div>
        <div>途径路线:{{item.routes.length===1?item.routes[0].routeDesc:`${item.routes[0].routeDesc} 至 ${item.routes[item.routes.length-1].routeDesc}`}}</div>
      </template>
    </app-list-dialog>
  </vant-form>
</template>

<script>

import { saveGovGeneralInfo } from '@apis/apply'
import { getXzqh } from '@apis/xzqh'
import { getHistoryRoutes } from '@apis/history'
import { search, historySearch, removeRoute, addRoute, updateShortName, createId } from './pass'
import mixin from './mixin'
import { Vant } from '@components/Vant/index'
export default {
  name: 'ApplyGeneralInfo',
  mixins: [mixin],
  data() {
    return {
      separatorRange: "至",
      value: "",
      maxRange: 6 * 30,
      form: this.curForm,
      list: [],
      show: false,
      historyList: [],
      passThrough: this.$store.getters['apply/passThrough']
    }
  },
  created() {
    this.getXzqh()

    this.setFormVal();
    this.saveGovGeneralInfo()
  },
  watch: {
    'form.date'(v) {
      if (v) {
        const [startDate, endDate] = v.split(this.separatorRange)
        this.$set(this.form, "startDate", startDate)
        this.$set(this.form, "endDate", endDate)
      }
    }
  },
  computed: {
    citys() {
      return this.list.map(item => {
        const { code, text, shortName } = item
        return { code, text, shortName }
      });
    },
    citysMap() {
      return this.list.reduce((o, cur) => {
        return o[cur.code] = cur, o
      }, {});
    }
  },
  methods: {
    getXzqh() {
      const city = this.$store.getters['xzqh/city']
      if (city.length) {
        this.list = city
      } else {
        getXzqh({ lvl: 2 }).then(res => {
          const { data = [] } = res || {};

          this.$store.dispatch('xzqh/setCity', data)
          this.list = data;
        })
      }
    },
    data2date({ startDate, endDate } = {}) {
      if (startDate && endDate) {
        this.$set(this.form, "date", startDate + this.separatorRange + endDate)
      } else {
        this.$set(this.form, "date", '')
      }
    },
    setFormVal(data = {}) {
      (this.$set(this.form, 'passThrough', data["passThrough"] ? data["passThrough"] : '1'));
      ['beginDist', 'endDist',].forEach(key => {
        this.$set(this.form, key, data[key] ? data[key] : '')
      });

      ['passDists'].forEach(key => {
        this.$set(this.form, key, data[key] ? data[key] : [])
      });

      this.data2date(data)
    },
    saveGovGeneralInfo() {
      saveGovGeneralInfo().then(res => {
        const { data = {} } = res || {};
        if (data.passDists && data.passDists.length) {
          data.passDists = data.passDists.map(item => {
            /* ['shortName', 'text','code'].forEach(key => {
              route[key] = item[key]
            }); */
            const info = this.citysMap[item.distCode] || {}
            return {
              ...item,
              ...info,
              _id: createId()
            }
          })
        }
        this.setFormVal(data);
      })
    },
    validator() { //校验函数返回 true 表示校验通过，false 表示不通过
      const { passDists } = this.form;
      let flag = !!(passDists && passDists.length)
      /* if(!flag){
        Vant.Toast(`请识别路线`);
        return flag
      } */
      /* flag=passDists.every(item=>Object.keys(item).every(key=>item[key]))
      if(!flag){
        Vant.Toast(`请识别正确路线`);
        return flag
      } */
      return flag
    },
    onSearch() {
      this.form.passDists = search(this.value, this.citys, this.citysMap) || [];
      this.$nextTick(() => {
        this.$refs.form.validate('passDists')
      })
    },
    submit() {
      return Promise.resolve(this.form);
    },
    add(route) {
      addRoute(route, this.form.passDists)
    },
    remove(route) {
      removeRoute(route, this.form.passDists)
    },
    confirm(item, route) {
      ['shortName', 'text', 'code'].forEach(key => {
        route[key] = item[key]
      });
      updateShortName(this.citys, route, this.form.passDists);
    },
    showHistory() {
      if (!this.form.beginDist) {
        Vant.Toast(`请选择起点`);
        return;
      } else if (!this.form.endDist) {
        Vant.Toast(`请选择终点`);
        return;
      }

      this.show = true;
      this.getHistoryList()
    },
    getHistoryList() {
      const p = getHistoryRoutes().then(res => {
        const { data = [] } = res || {}
        this.historyList = data;
      }).then(() => {
        return { isFinished: true }
      })
      this.$refs.dialog.getData(p);
    },
    changeRoute(/* item */) {
      /*  
       let s = ` 北京：起点 -- 太海路 -- 回南路 -- G15;
       河北：G18荣乌高速  --  冀津界；
       天津：S5津晋高速  --  宾水道  --  终点;` 
       this.form.passDists = search(s) || []; */
      let arr = [
        { "distCode": "110000", "text": "北京市", "beginPoint": "123", "routeDesc": "太海路-回南路-G15" },
        { "distCode": "130000", "text": "河北省", "routeDesc": "G18荣乌高速-冀津界" },
        { "distCode": "120000", "text": "天津市", "endPoint": "456", "routeDesc": "S5津晋高速-宾水道-终点" }
      ];
      this.form.passDists = historySearch(this.citys, arr) || [];
      this.$nextTick(() => {
        this.$refs.form.validate('passDists')
      })
    }
  }
}
</script>

<style lang="less" scoped>
.passDists {
  & > li {
    width: 100%;
  }
  .van-swipe-cell {
    width: 100%;
    & /deep/ .van-swipe-cell__wrapper {
      display: flex;
      align-items: center;
    }
  }
  .city,
  .start,
  .route,
  .end {
    display: block;
    font-size: @font-size;
    padding-left: 2px;
    padding-right: 2px;
    & /deep/ .van-cell {
      padding-left: 0;
      padding-right: 0;
    }
  }
  .city {
    width: 5em;
    & /deep/ .van-field__control {
      text-align: center;
    }
  }
  .start {
    width: 4em;
  }
  .end {
    width: 4em;
  }

  .delete-button {
    height: 100%;
  }
}
/* .history-btn-box {
  margin: 10px auto;
  text-align: center;
  .history-btn {
    display: inline-block;
    vertical-align: top;
    padding: 2px 0;
    border-bottom: 1px solid;
  }
} */
.pass-item {
  & /deep/ .van-cell:after {
    display: none;
  }
}
</style>